<template>
	<view>
		<nav-bar ref="navBar" :title="type === 'edit' ? '编辑地址' : '新增地址'" />
		<view class="li-box">
			<view class="title">联系人</view>
			<input type="text" v-model="form.userName" placeholder="姓名"/>
		</view>
		<view class="li-box">
			<view class="title">手机号</view>
			<input maxlength="11" type="number" v-model="form.phone" placeholder="请输入手机号"/>
			<button class="getPhone" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"
				:style="{ borderColor: themeColor, color: themeColor }">自动填写</button>
		</view>
		<view class="li-box" @click="getSettingFun">
			<view class="title">地址</view>
			<input type="text" disabled style="width: 79%;" v-model="form.address" />
			<view class="iconfont icon-xiangyoujiantou"></view>
		</view>
		<view class="li-box">
			<view class="title">门牌号</view>
			<input type="text" style="width: 80%;" v-model="form.addressDetail" placeholder="例:xx小区5号楼203"/>
		</view>
		<button @click="saveForm" class="savebtn" hover-class="btnActive"
			:style="{ backgroundColor: themeColor }">保存</button>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import {
		addressAdd,
		addressUpdate,
		getPhone
	} from '@/service/api/sp-address/index';
	import {
		TENCENT_MAP_KEY
	} from '@/const/address/key';
	export default {
		computed: {
			...mapState('sp-common/base', ['themeColor']),
			...mapState('sp-address/location', ['currentLocation'])
		},
		data() {
			return {
				type: '',
				editDetail: '', //编辑携带的详情
				form: {
					userName: '',
					phone: '',
					address: '',
					addressDetail: '',
					longitude: '',
					latitude: '',

					province: '',
					city: '',
					country: ''
				}
			};
		},
		onLoad() {
			this.initFunc();
		},
		methods: {
			//初始化
			initFunc() {
				let {
					type,
					data
				} = this.$Route.query;
				this.type = type;
				this.editDetail = data
				uni.setNavigationBarTitle({
					title: this.type === 'edit' ? '编辑地址' : '新增地址'
				});
				if (this.type === 'edit') {
					let {
						id,
						userName,
						phone,
						province,
						city,
						country,
						street,
						detail,
						longitude,
						latitude
					} = data;
					this.form.id = id;
					this.form.userName = userName;
					this.form.phone = phone;
					this.form.address = province + city + country + street;
					this.form.addressDetail = detail;

					this.form.longitude = longitude;
					this.form.latitude = latitude;
					this.form.province = province;
					this.form.city = city;
					this.form.country = country;
					this.form.street = street;
				} else {
					let {
						province,
						city,
						district,
						street
					} = this.currentLocation.address_info;
					this.form.province = province;
					this.form.city = city;
					this.form.country = district;
					this.form.street = street;
				}
			},
			// 调起位置
			getSettingFun() {
				let that = this;
				uni.getSetting({
					success(res) {
						if (!res.authSetting['scope.userLocation']) {
							uni.showModal({
								content: '检测到您没打开获取信息功能权限，是否去设置打开？',
								confirmText: "确认",
								cancelText: '取消',
								success(res) {
									console.log('openSetting', res);
									if (res.confirm) {
										uni.openSetting({
											success: (res) => {
												console.log(res);
											}
										})
									} else {
										console.log('取消');
									}
								}
							})
						} else {
							that.chooseLocationFun();
						}
					}
				});
			},
			chooseLocationFun() {
				let that = this;
				uni.chooseLocation({
					latitude: that.editDetail ? that.editDetail.latitude : undefined,
					longitude: that.editDetail ? that.editDetail.longitude : undefined,
					success: function(res) {
						console.log('选择位置', res);
						that.form.longitude = res.longitude;
						that.form.latitude = res.latitude;
						that.handleGetNearbyLocation(res.latitude, res.longitude);
					}
				});
			},

			// 获取省市区
			handleGetNearbyLocation(latitude, longitude) {
				uni.request({
					url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${TENCENT_MAP_KEY}`,
					success: res => {
						console.log('省市区', res);
						if (res.statusCode === 200) {
							let {
								province,
								city,
								district,
								street_number
							} = res.data.result.address_component;
							let {
								title
							} = res.data.result.address_reference.landmark_l2;
							this.form.province = province;
							this.form.city = city;
							this.form.country = district;
							this.form.street = street_number + title;
							this.form.address = province + city + district + street_number + title;
						}
					}
				});
			},

			// 调起授权手机号
			getPhoneNumber(e) {
				let data = {
					ivStr: e.detail.iv,
					encryptedData: e.detail.encryptedData
				};
				getPhone(data).then(res => {
					if (res) {
						this.form.phone = res;
					} else {
						uni.showToast({
							title: '手机号获取失败,请稍后重试',
							icon: 'none'
						});
					}
				});
			},

			// 校验表单
			checkForm() {
				return new Promise(resolve => {
					if (!this.form.userName) {
						uni.showToast({
							title: '联系人不能为空',
							icon: 'none',
							duration: 2000
						});
					} else if (!this.form.phone) {
						uni.showToast({
							title: '手机号不能为空',
							icon: 'none',
							duration: 2000
						});
					} else if (!(/^1[3456789]\d{9}$/.test(this.form.phone))) {
						uni.showToast({
							title: '请填写正确的手机号',
							icon: 'none',
							duration: 2000
						});
					} else if (!this.form.address) {
						uni.showToast({
							title: '地址不能为空',
							icon: 'none',
							duration: 2000
						});
					} else if (!this.form.addressDetail) {
						uni.showToast({
							title: '门牌号不能为空',
							icon: 'none',
							duration: 2000
						});
					} else {
						resolve(true)
					}
				})
			},

			// 保存
			async saveForm() {
				let that = this;
				let params = {
					id: this.form.id,
					// 城市
					city: this.form.city,
					// 地区
					country: this.form.country,
					// 门牌号
					detail: this.form.addressDetail,
					// 纬度
					latitude: this.form.latitude,
					// 经度
					longitude: this.form.longitude,
					// 手机号
					phone: this.form.phone,
					// 省份
					province: this.form.province,
					// 街道
					street: this.form.street,
					// 收货人名称
					userName: this.form.userName
				};

				let checkForm = await this.checkForm()
				if (checkForm) {
					if (this.type === 'edit') {
						addressUpdate(params)
							.then(res => {
								this.submitToast('success')
							})
							.catch(err => {
								this.submitToast(err)
							});
					} else {
						addressAdd(params)
							.then(res => {
								this.submitToast('success')
							})
							.catch(err => {
								this.submitToast(err)
							});
					}
				}
			},

			// 提交成功并返回
			submitToast(data) {
				if (data === 'success') {
					uni.showToast({
						title: '提交成功',
						duration: 2000
					});
					setTimeout(() => {
						this.$Router.back(0);
					}, 2000);
				} else {
					uni.showToast({
						title: data,
						icon: 'none',
						duration: 2000
					});
				}
			}
		}
	};
</script>

<style>
	page {
		background-color: #f7f7f7;
	}
</style>
<style lang="scss" scoped>
	.li-box {
		width: 100%;
		overflow: hidden;
		border-top: 1rpx solid #f3f3f3;
		padding: 20rpx;
		box-sizing: border-box;
		background-color: white;

		.title {
			color: #181818;
			font-size: 32rpx;
			font-weight: 500;
			width: 15%;
			float: left;
		}

		input {
			font-size: 29rpx;
			font-weight: 500;
			color: #181818;
			padding: 0 40rpx;
			box-sizing: border-box;
			width: 60%;
			float: left;
		}

		.getPhone {
			height: 42rpx;
			border: 1rpx solid #ccc;
			border-radius: 8rpx;
			line-height: 39rpx;
			font-size: 24rpx;
			float: right;
		}

		button::after {
			border: 0;
		}

		.iconfont {
			margin-top: 7rpx;
			float: right;
			width: 11px;
			height: 19px;
			color: #c0c0c0;
		}
	}

	.savebtn {
		width: 600rpx;
		height: 80rpx;
		border-radius: 40rpx;
		font-size: 32rpx;
		font-weight: 500;
		color: #ffffff;
		text-align: center;
		line-height: 80rpx;
		margin: 70rpx auto;
	}

	.btnActive {
		opacity: 0.5;
	}
</style>
